package com.graph;

import java.util.LinkedList;

public class Solution990 {
    int[] father;

    public boolean equationsPossible(String[] equations) {
        father = new int[26];
        for (int i = 0; i < 26; i++) {
            father[i] = i;
        }
        for (String s : equations) {
            if (s.charAt(1) == '=') {
                join(s.charAt(0) - 'a', s.charAt(3) - 'a');
            }
        }
        for (String s : equations) {
            if (s.charAt(1) == '!') {
                if (same(s.charAt(0) - 'a', s.charAt(3) - 'a')) return false;
            }
        }
        return true;
    }

    public int find(int x) {
        if (x == father[x]) return x;
        father[x] = find(father[x]);
        return father[x];
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
    }
}
